use super::EditorApp;
use crate::chess::*;
use eframe::{self, egui};

impl EditorApp {
    pub fn show_book_dialog(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
        let mut action_performed = false;
        let mut is_menu_open = self.is_menu_open;
        egui::Window::new("棋谱菜单")
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::new(0.0, -60.0))
            .open(&mut is_menu_open)
            .show(ctx, |ui| {
                ui.vertical_centered(|ui| {
                    ui.add_space(10.0);
                    if ui.button("　打开棋谱　").clicked() {
                        action_performed = self.open_book_file(frame);
                    }
                    ui.add_space(10.0);
                    if ui.button("　保存棋谱　").clicked() {
                        action_performed = self.save_book_file(Some(frame));
                    }
                    ui.add_space(10.0);
                    if ui.button("　导入棋谱　").clicked() {
                        if let Some(file) = rfd::FileDialog::new()
                            .add_filter("棋谱文件", &["xqb"])
                            .pick_file()
                        {
                            match Book::load_from_text(&file) {
                                Ok(book) => {
                                    self.session.import_book(&book);
                                    self.update_window_title(frame);
                                    action_performed = true;
                                }
                                Err(err) => super::show_error_message("错误", &format!("{}", err)),
                            }
                        }
                    }
                    ui.add_space(10.0);
                });
            });
        if action_performed || !is_menu_open {
            self.is_menu_open = false;
        }
    }
}
